/*
 *  Copyright 2015 The WebRTC Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

package com.cloudptt.wp.ui.call.group;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.func.call.CallConst;
import com.cloudptt.api.product.func.call.group.fsm.GroupCallConferenceListener;
import com.cloudptt.api.product.func.call.group.fsm.video.GroupCallMemberInfo;
import com.cloudptt.api.product.func.call.single.LaunchCallInfo;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.AddrOperator;
import com.cloudptt.wp.R;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.UiDlg;
import com.cloudptt.wp.ui.message.adapter.GroupMemberAdapter;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.GroupMembInfo;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Fragment for call control.
 */
public class GroupCallFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener, GroupCallConferenceListener {
	//	public static String THIS_FILE = "CallFragment";

	private Context ctx = null;
	private View controlView;

	private RelativeLayout mAcceptRLayout;
	private RelativeLayout mDisconnectRLayout;
	private ImageButton acceptButton;
	private ImageButton disconnectButton;
//	private GroupCallSelfLy selfLy = null;
	private ListView memberListView;
	private Button transBtn = null;
	private Button membListBtn = null;
	private Button recvBtn = null;
	private OnCallEvents callEvents;
	private LaunchCallInfo callInfo = null;
	private AddrInfo peerAddrInfo = null;
	private int curCallState = CallConst.CallState_InitState;
	private boolean isTransBegin = false;
	private boolean isRecvBegin = false;
//	private List<GroupMembInfo> membList = null;
	private List<GroupCallMemberInfo> groupCallMemberInfoList = null;
	private GroupCallMemberListAdapter adapter = null;
//	private GroupCallMemberInfo selfInfo = null;
	private List<GroupMembInfo> membList = null;
	//	private GroupCallMemberInfo info = new GroupCallMemberInfo();
	private GroupMemberAdapter groupMemberAdapter = null;
	private AlertDialog dlg = null;

	public GroupCallFragment(Context ctx, LaunchCallInfo callInfo,AddrInfo peerAddrInfo,OnCallEvents callEvents)
	{
		this.ctx = ctx;
		this.callInfo = callInfo;
		this.peerAddrInfo = peerAddrInfo;
		this.callEvents = callEvents;
		initSelfInfo();
	}

	/**
	 * Call control interface for container activity.
	 */
	public interface OnCallEvents {
		public void doUserAction(int btnAction,String infoStr);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		Log.debug(this.getClass(), "onCreateView");
		controlView =
				inflater.inflate(R.layout.fragment_call_group, container, false);

//		selfLy = (GroupCallSelfLy) controlView.findViewById(R.id.selfLy);
//		if(selfInfo != null)
//		{
//			selfLy.updateSelfGroupCallMemberInfo(selfInfo);
//		}
		memberListView = (ListView) controlView.findViewById(R.id.memberListView);
		adapter = new GroupCallMemberListAdapter(ctx, groupCallMemberInfoList,callEvents);
		memberListView.setAdapter(adapter);
		memberListView.setOnItemClickListener(this);

		transBtn =
				(Button) controlView.findViewById(R.id.transBtn);
		membListBtn =
				(Button) controlView.findViewById(R.id.membListBtn);
		recvBtn =
				(Button) controlView.findViewById(R.id.recvBtn);
		transBtn.setOnClickListener(this);
		membListBtn.setOnClickListener(this);
		recvBtn.setOnClickListener(this);

		mAcceptRLayout =
				(RelativeLayout) controlView.findViewById(R.id.rl_accept);
		acceptButton =
				(ImageButton) controlView.findViewById(R.id.button_call_accept);
		mDisconnectRLayout =
				(RelativeLayout) controlView.findViewById(R.id.rl_disconnect);
		disconnectButton =
				(ImageButton) controlView.findViewById(R.id.button_call_disconnect);
		acceptButton.setOnClickListener(this);
		disconnectButton.setOnClickListener(this);
//		mCameraRLayout =
//				(RelativeLayout) controlView.findViewById(R.id.rl_switch_camera);
//		cameraSwitchButton =
//				(ImageButton) controlView.findViewById(R.id.button_call_switch_camera);
//		if(callInfo != null
//				&& callInfo.isHasVideo())
//		{
//			cameraSwitchButton.setVisibility(View.VISIBLE);
//		}
//		else
//		{
//			cameraSwitchButton.setVisibility(View.INVISIBLE);
//		}
//
//		enableMicIb =
//				(ImageButton) controlView.findViewById(R.id.enableMicIb);
//		enableMicIb.setEnabled(enableMic);
//		enableMicIb.setVisibility(View.INVISIBLE);
//
//		enableSpeakerIb =
//				(ImageButton) controlView.findViewById(R.id.enableSpeakerIb);
//		enableSpeakerIb.setEnabled(enableSpeaker);
//		 Add buttons click events.



		return controlView;
	}

	private void initSelfInfo()
	{
		SysApplication app = ((SysApplication) ctx.getApplicationContext());
		Product product = app.getProduct();
		AddrOperator op = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
		AddrInfo selfAddrInfo= product.getSysConfig().getMcInfo().toAddrInfo();
//		selfInfo = new GroupCallMemberInfo(selfAddrInfo,"");
		product.setGCallConferenceListener(this);
	}

	@Override
	public void onClick(View v) {
		Log.debug(this.getClass(), "onClick v.getId() = " + v.getId());
		if(R.id.button_call_accept == v.getId())
		{
			callEvents.doUserAction(CallConst.BtnAction_Answer,"");
		}
		else if(R.id.button_call_disconnect == v.getId())
		{
			callEvents.doUserAction(CallConst.BtnAction_Hangup,"");
		}
		else if(R.id.transBtn == v.getId())
		{
			if(!isTransBegin)
			{
				callEvents.doUserAction(CallConst.BtnAction_Trans_Begin,"");
				transBtn.setEnabled(false);
//				isTransBegin = true;
			}
			else
			{
				callEvents.doUserAction(CallConst.BtnAction_Trans_End,"");
				transBtn.setEnabled(false);
//				isTransBegin = false;
			}
		}
		else if(R.id.recvBtn == v.getId())
		{
			if (adapter != null) {
				int position = adapter.getSelectedPos();
				Log.debug(this.getClass(), "onClick recvBtn position = " + position);
				if (groupCallMemberInfoList != null
						&& groupCallMemberInfoList.size() > position
						&& groupCallMemberInfoList.get(position) != null)
				{
					GroupCallMemberInfo info = groupCallMemberInfoList.get(position);
					Log.debug(this.getClass(), "onClick recvBtn info = " + info);
					if(info.isTrans()) {
						String jsonStr = info.getJsonStr();
//						if (!isRecvBegin) {
//							callEvents.doUserAction(CallConst.BtnAction_Recv_Begin, jsonStr);
//							isRecvBegin = true;
//						} else
						if (isRecvBegin)
						{
							callEvents.doUserAction(CallConst.BtnAction_Recv_End, jsonStr);
							recvBtn.setEnabled(false);
//							isRecvBegin = false;
						}
					}
				}
			}
		}
//		else if(R.id.transListBtn == v.getId())
//		{
//			String[] list = getTransListDesp();
//			Log.debug(this.getClass(), "onClick transListBtn list = " + list);
////			String[] list = new String[]{"111","222"};
//			if(list != null
//				&& list.length > 0) {
//				UiDlg.showListDialog(ctx, list, this);
//			}
//			else
//			{
//				CommDlg.showToast(ctx,R.string.group_call_list_null);
//			}
//		}
		else if(R.id.membListBtn == v.getId())
		{
			Log.debug(this.getClass(), "onClick membListBtn peerAddrInfo = " + peerAddrInfo);
			SysApplication app = ((SysApplication) ctx.getApplicationContext());
			Product product = app.getProduct();
			product.getGCallEventAdapter().subcribeConference();
			AddrOperator op = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
			String selfAddrId = product.getSysConfig().getMcInfo().getAddrId();
			membList = op.getGroupMemberList(peerAddrInfo,selfAddrId);
			Log.debug(this.getClass()," onCreate membList = " + membList);
			groupMemberAdapter = new GroupMemberAdapter(ctx, true,membList);
			dlg = UiDlg.getAdapterListDialog(ctx,groupMemberAdapter);
			dlg.show();
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.debug(this.getClass(), "onStart callInfo = " + callInfo);
		boolean captureSliderEnabled = false;
		//    String contactName = args.getString(CallActivity.EXTRA_IP);
		//    contactView.setText(contactName);
		//    videoCallEnabled = args.getBoolean(CallActivity.EXTRA_VIDEO_CALL, true);
		//    videoCallEnabled = para.isVideoCallEnabled();
		captureSliderEnabled = false;//videoCallEnabled && para.isCaptureQualitySlider();
//		if (!videoCallEnabled) {
//			cameraSwitchButton.setVisibility(View.INVISIBLE);
//		}
		if (captureSliderEnabled) {
//			captureFormatSlider.setOnSeekBarChangeListener(
//					new CaptureQualityController(captureFormatText, callEvents));
		}
		int callState = callInfo.getCallState();
		Log.debug(this.getClass(), "onStart callState = " + callState);
		updateView(callState);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		callEvents = (OnCallEvents) activity;
	}

	public void updateTransState(int state)
	{
		Log.debug(this.getClass(), "updateTransState state = " + state);
		if(CallConst.VideoTransState_NoPermission == state)
		{
			isTransBegin = false;
			transBtn.setText(R.string.group_call_trans_begin);
			transBtn.setEnabled(true);
		}
		else if(CallConst.VideoTransState_Permission == state)
		{
			isTransBegin = true;
			transBtn.setText(R.string.group_call_trans_end);
			transBtn.setEnabled(true);
		}
		Log.debug(this.getClass(), "updateTransState state = " + state + " isTransBegin = "  + isTransBegin + " isRecvBegin = " + isRecvBegin);
//		if(selfLy != null) {
//			selfInfo.update(isTransBegin,isRecvBegin);
////			selfLy.updateSelfGroupCallMemberInfo(selfInfo);
//			selfLy.updateTransState(state);
//		}
	}

	public void updateRecvState(int state)
	{
		Log.debug(this.getClass(), "updateRecvState state = " + state);
		if(CallConst.VideoRecvState_NoPermission == state)
		{
			isRecvBegin = false;
			recvBtn.setText(R.string.group_call_recv_begin);
			recvBtn.setEnabled(false);
			if(adapter != null)
			{
				adapter.setIsView(false);
				adapter.notifyDataSetChanged();
			}
		}
		else if(CallConst.VideoRecvState_Permission == state)
		{
			recvBtn.setEnabled(true);
			isRecvBegin = true;
			recvBtn.setText(R.string.group_call_recv_end);
			Log.debug(this.getClass(), "updateRecvState isRecvBegin = " + isRecvBegin);
			if(adapter != null)
			{
				adapter.setIsView(true);
				adapter.notifyDataSetChanged();
			}
		}
		Log.debug(this.getClass(), "updateRecvState state = " + state + " isTransBegin = "  + isTransBegin + " isRecvBegin = " + isRecvBegin);
//		if(selfLy != null) {
//			selfInfo.update(isTransBegin,isRecvBegin);
////			selfLy.updateSelfGroupCallMemberInfo(selfInfo);
//			selfLy.updateRecvState(state);
//		}
	}

	public void updateGroupCallMemberInfoList(List<GroupCallMemberInfo> groupCallMemberInfoList)
	{
		this.groupCallMemberInfoList = groupCallMemberInfoList;
		if(adapter != null) {
			adapter.refresh(groupCallMemberInfoList);
			adapter.notifyDataSetChanged();
		}
	}


	public void updateView(int callState)
	{
		Log.debug(this.getClass(), "updateView callState = " + callState);
		if(callState == CallConst.CallState_Activite)
		{
			this.viewOnConnected();
			transBtn.setVisibility(View.VISIBLE);
			membListBtn.setVisibility(View.VISIBLE);
			recvBtn.setVisibility(View.VISIBLE);
		}
		else //if(callState == CallConst.CallState_ConnectingState)
		{
			if(callInfo.isMoCall())
			{
				viewOnCalling();
			}
			else
			{
				viewOnIncoming();
			}
			transBtn.setVisibility(View.GONE);
			membListBtn.setVisibility(View.GONE);
			recvBtn.setVisibility(View.GONE);
			if(dlg != null) {
				dlg.dismiss();
			}
		}
//		else if(callState == CallConst.CallState_InitState)
//		{
//			if(dlg != null) {
//				dlg.dismiss();
//			}
//		}
	}

	public void viewAfterOffer()
	{
		mAcceptRLayout.setEnabled(true);

	}
	private void viewOnCalling()
	{
		Log.debug(this.getClass(), "viewOnCalling");
		//acceptButton.setVisibility(View.GONE);
		//disconnectButton.setVisibility(View.VISIBLE);
		//cameraSwitchButton.setVisibility(View.GONE);
		//toggleMuteButton.setVisibility(View.GONE);

		if(mAcceptRLayout != null)
		{
			mAcceptRLayout.setVisibility(View.GONE);
		}
		if(mDisconnectRLayout != null)
		{
			mDisconnectRLayout.setVisibility(View.VISIBLE);
		}
//		mCameraRLayout.setVisibility(View.GONE);
//		mToggleMuteRLayout.setVisibility(View.GONE);

	}

	private void viewOnIncoming()
	{
		Log.debug(this.getClass(), "viewOnIncoming");
		/*acceptButton.setVisibility(View.VISIBLE);
	  disconnectButton.setVisibility(View.VISIBLE);
	  cameraSwitchButton.setVisibility(View.GONE);
	  toggleMuteButton.setVisibility(View.GONE);*/
		if(mAcceptRLayout != null) {
			mAcceptRLayout.setVisibility(View.VISIBLE);
		}
		if(mDisconnectRLayout != null) {
			mDisconnectRLayout.setVisibility(View.VISIBLE);
		}
//		mCameraRLayout.setVisibility(View.GONE);
//		mToggleMuteRLayout.setVisibility(View.GONE);
	}

	public void viewOnConnected()
	{
		Log.debug(this.getClass(), "viewOnConnected");
		/*acceptButton.setVisibility(View.GONE);
	  disconnectButton.setVisibility(View.VISIBLE);
	  cameraSwitchButton.setVisibility(View.VISIBLE);
	  toggleMuteButton.setVisibility(View.VISIBLE);*/

		if(mAcceptRLayout != null) {
			mAcceptRLayout.setVisibility(View.GONE);
		}
		if(mDisconnectRLayout != null) {
			mDisconnectRLayout.setVisibility(View.VISIBLE);
		}
//		mCameraRLayout.setVisibility(View.VISIBLE);
//		mToggleMuteRLayout.setVisibility(View.VISIBLE);
	}

	public void setCallState(LaunchCallInfo callInfo) {
		Log.debug(this.getClass(), "setCallState callInfo = " + callInfo);
		if(callInfo != null)
		{
			this.callInfo = callInfo;
			int callState = callInfo.getCallState();
			Log.debug(this.getClass(), "setCallState callState = " + callState + " curCallState = " + curCallState);
			if(curCallState <= callState) {
				curCallState = callState;
				Log.debug(this.getClass(), "setCallState callState = " + callState);
				updateView(callState);
			}
		}
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//		if(transUserInfoList != null
//			&& transUserInfoList.get(position) != null)
//		{
//			GroupCallMemberInfo info = transUserInfoList.get(position);
//			String jsonStr = info.getJsonStr();
//			callEvents.doUserAction(CallConst.BtnAction_Recv_Begin,jsonStr);
//			isRecvBegin = true;
//		}
		if(adapter != null)
		{
			adapter.setSelectedPos(position);
		}
	}

	@Override
	public void updateConferenceInfoList(String groupAddrId, boolean isFull,Map<String, Boolean> conferenceInfoMap) {
		Log.debug(this.getClass(),"updateConferenceInfoList groupAddrId =  "+ groupAddrId +" isFull = "+isFull +  " conferenceInfoMap = " + conferenceInfoMap);

		new Handler(Looper.getMainLooper()).post(() -> {
			if(groupMemberAdapter != null)
			{
				groupMemberAdapter.refresh(isFull,conferenceInfoMap);
				groupMemberAdapter.notifyDataSetChanged();
			}
		});

	}
	private boolean isHas(GroupMembInfo info )
	{
		Log.debug(this.getClass(),"isHas info =  "+ info +" membList = " + membList);
		for (Iterator<GroupMembInfo> itor = membList.iterator(); itor.hasNext();)
		{
			GroupMembInfo membInfo = itor.next();
			String addrId = info.getAddrId();
			if(membInfo != null
					&& membInfo.isSameOne(addrId))
			{
				return true;
			}
		}
		return false;
	}

}
